package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.dto.EntryDto;
import com.heima.behavior.dto.UnLikesBehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApUnlikesBehavior;
import com.heima.behavior.mapper.ApUnlikesBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApUnlikesBehaviorService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP不喜欢行为表 服务实现类
 * </p>
 *
 * @author wsj
 * @since 2022-03-17
 */
@Service
public class ApUnlikesBehaviorServiceImpl extends ServiceImpl<ApUnlikesBehaviorMapper, ApUnlikesBehavior> implements IApUnlikesBehaviorService {
    @Autowired
    private IApBehaviorEntryService entryService;
    @Override
    public ResponseResult unlikeBehavior(UnLikesBehaviorDto dto) {
        //不喜欢或取消不喜欢
        //获取线程中的user
        User user = AppThreadLocalUtil.get();
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //保存实体
        EntryDto entryDto = new EntryDto();
        entryDto.setEquipmentId(dto.getEquipmentId());
        entryDto.setUserId(user.getId());
        ApBehaviorEntry entry = entryService.saveEntry(entryDto);
        //保存APP不喜欢行为表
        //构建条件查询是否存在
        LambdaQueryWrapper<ApUnlikesBehavior> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApUnlikesBehavior::getArticleId, dto.getArticleId());
        wrapper.eq(ApUnlikesBehavior::getEntryId, entry.getId());
        ApUnlikesBehavior behavior = getOne(wrapper);
        if (behavior!=null) {
            //存在，则更新
            behavior.setType(dto.getType());
        }else {
            //不存在，则新增
            behavior = new ApUnlikesBehavior();
            behavior.setType(dto.getType());
            behavior.setArticleId(Long.parseLong(dto.getArticleId()));
            behavior.setEntryId(entry.getId());
            behavior.setCreatedTime(new Date());
        }
        saveOrUpdate(behavior);
        return ResponseResult.okResult();

    }
}
